package com.pig4cloud.pig.ads.runner;

import com.pig4cloud.pig.ads.service.AdvPlanService;
import com.pig4cloud.pig.api.entity.AdPlan;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

@Slf4j
public class SynAdPlanWorker  implements Runnable {

	private AdvPlanService advPlanService;

	private String advertiserId;

	private Long adId;

	//最大重试次数
	private static final Integer tryTimes = 6;
	//重试间隔时间单位秒
	private static final Integer[] intervalTime = {15, 60, 120, 150, 300, 600};

	public SynAdPlanWorker(AdvPlanService advPlanService, String advertiserId, Long adId) {
		this.advPlanService = advPlanService;
		this.advertiserId = advertiserId;
		this.adId = adId;
	}


	@Override
	public void run() {

			this.fetchAdid();
	}


	private void fetchAdid(){
		try {
			Integer retryNum = 1;
			boolean flag = false;
			while (retryNum <= tryTimes) {
				try {
					advPlanService.getAdPlan(advertiserId, String.valueOf(adId));
					AdPlan adPlan = advPlanService.getById(adId);

					if (adPlan != null) {
						flag = true;
					} else {//redis没信息，算成功，不执行重新查询。只有userid为空的时候，重新执行查询
						log.info("计划拉取：{}拉取无信息...", adId);
						flag = false;
					}
					if (flag) {
						log.info("计划拉取：第" + retryNum + "次执行成功!!!");
						break;
					}
					TimeUnit.SECONDS.sleep(intervalTime[retryNum-1]);
					log.info("计划拉取：{}第{}次查询adid失败...", adId, retryNum);
					retryNum++;
				} catch (Throwable e) {
					retryNum++;
					TimeUnit.SECONDS.sleep(intervalTime[retryNum-1]);
					continue;
				}
			}
		}catch(Throwable e){
			log.error("拉取第三方广告计划失败", e);
		}
	}
}
